import React, { useState, useEffect } from 'react';
import { Input } from 'antd';
import TableEditor from 'src/components/TableEditor';
import { compare } from '../../../utils/compare';

const EnumConfig = (props) => {
  const { disabled, value } = props;
  const [data, setData] = useState([]);

  useEffect(() => {
    value && setData(value);
  }, [value]);

  const handleChange = (value, index, key) => {
    const temp = [...data];
    temp[index][key] = value;
    setData(temp);
    props.onChange && props.onChange(temp);
  };

  const handleEditorChange = (value) => {
    setData(value);
    props.onChange && props.onChange(value);
  };

  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      render: (_, __, index) => index + 1,
    },
    {
      title: '枚举CODE',
      dataIndex: 'code',
      render: (text, _, index) => (
        <Input
          value={text}
          onChange={(e) => handleChange(e.target.value, index, 'code')}
          style={compare(props, index, 'code')}
          disabled={disabled}
        />
      ),
    },
    {
      title: '枚举值',
      dataIndex: 'value',
      render: (text, _, index) => (
        <Input
          value={text}
          onChange={(e) => handleChange(e.target.value, index, 'value')}
          style={compare(props, index, 'value')}
          disabled={disabled}
        />
      ),
    },
  ];

  return (
    <div className='plr20'>
      <TableEditor
        dataSource={data}
        columns={columns}
        initItem={{ code: '', value: '' }}
        onChange={handleEditorChange}
        disabled={disabled}
        noNeedAdd={disabled}
        getButtonGroup={({ moveUpButton, moveDownButton, removeButton }) => {
          return [(moveUpButton, moveDownButton, removeButton)];
        }}
      />
    </div>
  );
};

export default EnumConfig;
